import { getAlarms } from '@/api/alarm';
const state = {
  alarms: [],
  alarmMsg: [],
  show: true
}

const mutations = {
  SET_ALARMS(state, alarms) {
    if (!alarms) return;
    state.alarms = alarms.rows;
    const msg = alarms.msg.split(',');
    const set = new Set(state.alarmMsg.concat(msg));
    state.alarmMsg = Array.from(set);
  },
  REMOVE_ALARMS(state) {
    state.alarms = [];
    state.alarmMsg = [];
  },
  REMOVE_ALARM(state, id) {
    state.alarms = state.alarms.filter(a => a.pkid !== id);
  },
  REMOVE_ALARM_MSG(state) {
    state.alarmMsg = [];
  },
  HIDDEN(state) {
    state.show = false
  },
  SHOW(state) {
    state.show = true
  }
}

const actions = {
  getAlarms({ commit }) {
    return new Promise(async resolve => {
      const alarms = await getAlarms();
      if (alarms && alarms.rows.length > 0) {
        commit('SET_ALARMS', alarms);
        resolve(alarms);
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
